import { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components'
import type { ProFormInstance } from '@ant-design/pro-components'
import { EditRoleFnc } from '@/services/roles'
import { message } from 'antd';
import { itemType } from './type'

const EditBox = ({isModalOpen, changeDialog, id, roleName, roleDesc, actionRef}: itemType) => {
  const formRef: any = useRef<ProFormInstance>()
  // 用于做比较的form
  const [formObj, setFormObj] = useState({})
  const [messageApi, contextHolder] = message.useMessage()

  // 打开编辑盒子
  useEffect(() => { 
    if(String(id) !== '' && isModalOpen === true)  formRef.current.setFieldsValue({roleName: roleName, roleDesc: roleDesc})
    setFormObj({roleName: roleName, roleDesc: roleDesc})    
  }, [id])
  
  // 修改角色
  const onFinish = async (value: {roleName: string, roleDesc: string}) => {
    if (JSON.stringify(formObj) === JSON.stringify(value)) {
        changeDialog(false);
    } else {
    const res = await EditRoleFnc(parseInt(id), value);
      if(res.meta.status === 200) {
        messageApi.success('修改成功', 1.5, () => {
          changeDialog(false)
          actionRef.current?.reload();
        })
      }
    }
  } 

  return (
    <>
      {contextHolder}
      <ModalForm formRef={formRef} title="编辑角色" width={500} layout="horizontal" labelCol={{ span: 4 }} open={isModalOpen} onFinish={onFinish} modalProps={{ onCancel: () => changeDialog(false) }}>
        <ProFormText name="roleName" label="角色名称" rules={[{ required: true, message: '请输入角色名称' }, {min: 3, max: 10, message: '长度在3-10个字符'}]}/>
        <ProFormText name="roleDesc" label="角色描述" rules={[{ required: true, message: '请输入角色描述' }, {min: 3, max: 10, message: '长度在3-10个字符'}]}/>
      </ModalForm>
    </>
  )
}

export default EditBox